//
//  TipsService.m
//  TipsProject
//
//  Created by Suny on 15/6/4.
//  Copyright (c) 2015年 Suny. All rights reserved.
//

#import "TipsService.h"
#import "TipImageItem.h"
#import "TipTextItem.h"
#import "TipAbstract.h"
#import "WaterFlowDisplayInfo.h"



@interface TipsService ()


@end

@implementation TipsService

- (void)getTipsFromServe:(NSString *)type withPageNumber:(NSInteger)pageNumber  finishBlock:(RequestFinishBlock)finishBlock
{
	[self getTipsFromServe:type 
					userId:[LoginUserInfo sharedInstance].userId
			withPageNumber:pageNumber
			   finishBlock:finishBlock];
}

- (void)getTipsFromServe:(NSString *)type userId:(NSString *)userId withPageNumber:(NSInteger)pageNumber  finishBlock:(RequestFinishBlock)finishBlock
{
	if (CHECK_VALID_STRING(type)&&CHECK_VALID_STRING(userId))
	{
		NSDictionary *dictionary = @{@"curPage":@(pageNumber),@"pageSize":@(kDefaultPageSize)};
		
		NSString *relativePath = [NSString stringWithFormat:@"%@/%@/%@",kGetTipsUrl,userId,type];
		
		WEAKSELF
		AFHTTPRequestOperation * requestOperation = [self beginGetRequestWithRelativePath:relativePath
																		  parameterObject:dictionary
																			responseClass:nil
																			  finishBlock:^(BaseResponse *response) 
													 {
														 NSMutableArray *resultArray = [NSMutableArray array];
														 NSArray *dicArray = [response.object objectForKey:@"pageContent"];
														 
														 for (NSDictionary *dic in dicArray)
														 {
															 TipAbstract *abstract = [[TipAbstract alloc] initWithSourceString:dic];
															 WaterFlowDisplayInfo *displayInfo = [WaterFlowDisplayInfo infoWithAbstract:abstract];
															 
															 [resultArray addObject:displayInfo];
														 }
														 response.object = resultArray;
														 
														 finishBlock(response);
														 [weakSelf removeWrapperForKey:kGetTipsUrl];
														 
														 
													 }];
		
		[self setWrapper:requestOperation
				  ForKey:kGetTipsUrl];
	}
}

- (void)getCollectTips:(NSInteger)pageNumber  finishBlock:(RequestFinishBlock)finishBlock
{
	[self getTipsFromServe:@"collect" 
			withPageNumber:pageNumber
			   finishBlock:finishBlock];
	
}

- (void)getCollectTips:(NSInteger)pageNumber userId:(NSString *)userId finishBlock:(RequestFinishBlock)finishBlock
{
	[self getTipsFromServe:@"collect" 
					userId:userId
			withPageNumber:pageNumber
			   finishBlock:finishBlock];
}


- (void)getCreateTips:(NSInteger)pageNumber  finishBlock:(RequestFinishBlock)finishBlock
{
	[self getTipsFromServe:@"create" 
			withPageNumber:pageNumber
			   finishBlock:finishBlock];
}

- (void)getCreateTips:(NSInteger)pageNumber userId:(NSString *)userId  finishBlock:(RequestFinishBlock)finishBlock
{
	[self getTipsFromServe:@"create" 
					userId:userId
			withPageNumber:pageNumber
			   finishBlock:finishBlock];
}

- (void)getPraiseTips:(NSInteger)pageNumber  finishBlock:(RequestFinishBlock)finishBlock
{
	[self getTipsFromServe:@"praise" 
			withPageNumber:pageNumber
			   finishBlock:finishBlock];
}

- (void)getHotTips:(NSInteger)pageNumber  finishBlock:(RequestFinishBlock)finishBlock
{
	[self getTipsFromServe:@"hot" 
			withPageNumber:pageNumber
			   finishBlock:finishBlock];
}



- (void)getInterestedTips:(NSInteger)pageNumber  finishBlock:(RequestFinishBlock)finishBlock
{
	[self getTipsFromServe:@"interested"
            withPageNumber:pageNumber
			   finishBlock:finishBlock];
}

- (void)getInterestedTips:(NSInteger)pageNumber userId:(NSString *)userId finishBlock:(RequestFinishBlock)finishBlock
{
    [self getTipsFromServe:@"interested"
            userId:userId
            withPageNumber:pageNumber
               finishBlock:finishBlock];
}



- (void)publishTipToServe:(TipInfo *)tipInfo finishBlock:(RequestFinishBlock)finishBlock
{
	NSDictionary *dictionary = @{@"memberId":[ NSString stringWithFormat:@"%@",[LoginUserInfo sharedInstance].userId ],
								 @"title":tipInfo.title,
								 @"categoryId":tipInfo.categoryId,
								 @"attachmentNum":[NSString stringWithFormat:@"%lu",(unsigned long)[tipInfo.fileArray count]]};
	
	dictionary = [[NSMutableDictionary alloc] initWithDictionary:dictionary];
	

	WEAKSELF
	
	AFHTTPRequestOperation * requestOperation = [self beginRequestWithRelativePath:kPublishTipsUrl 
																   parameterObject:dictionary
																		 fileArray:tipInfo.fileArray
																	 responseClass:nil
																	   finishBlock:^(BaseResponse *response) {
																		   finishBlock(response);
																		   [weakSelf removeWrapperForKey:kPublishTipsUrl];

																	   }];
	[self setWrapper:requestOperation
			  ForKey:kPublishTipsUrl];
}





- (AFHTTPRequestOperation *)beginRequestWithRelativePath:(NSString *)relativePath
										 parameterObject:(id)object
											   fileArray:(NSArray *)fileArray
										   responseClass:(NSString *)className
											 finishBlock:(RequestFinishBlock)finishBlock
{
	//发送数据字典
	NSMutableDictionary *temPostDictionary = [NSMutableDictionary dictionary];
	
	if ([object isKindOfClass:[NSDictionary class]])
	{
		[temPostDictionary setDictionary:object];
	}
	else
	{
		if ([object isKindOfClass:[BaseEntity class]])
		{
			NSDictionary *temDic = [object dictionaryForJson];
			if (!temDic)
			{
				temDic = [object getPropertyNameAndValue];
			}
			[temPostDictionary setDictionary:temDic];
		}
	}
	
	
	NSString *urlString = [NSString stringWithFormat:@"%@%@",
						   self.baseUrlString,
						   relativePath];
	NSString *temString = [self.defaultRequestParameterDictionary createStringUrlParameter];
	
	NSMutableURLRequest *request = nil;
	
	{
		
		NSMutableDictionary *fileDictionary = [NSMutableDictionary dictionary];
		
		
	 [temPostDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
		 if ([obj isKindOfClass:[NSData class]])
		 {
			 [fileDictionary setObject:obj forKey:key];
		 }
		 else if ([obj isKindOfClass:[UIImage class]])
		 {
			 NSData *data =  UIImageJPEGRepresentation((UIImage *)obj, 1);
			 [fileDictionary setObject:data forKey:key];
			 
		 }
	 }];
		
		
		
		{
			[temPostDictionary removeObjectsForKeys:[fileDictionary allKeys]];
			
			AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
			
			request = [requestSerializer multipartFormRequestWithMethod:@"POST"
															  URLString:urlString
															 parameters:temPostDictionary
											  constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
												  int count = 0;
												  for (TipItem *item in fileArray)
												  {
													  count ++;
													  if ([item isKindOfClass:[TipImageItem class]]) 
													  {
														  TipImageItem *imageItem = (TipImageItem *)item;
														  NSData *fileData = UIImageJPEGRepresentation(imageItem.image, 1);
														  [formData appendPartWithFileData:fileData
																					  name:[NSString stringWithFormat:@"%d",count] 
																				  fileName:[NSString stringWithFormat:@"%d.jpg",count]
																				  mimeType:@"image/jpeg"];
													  }
													  else 	if ([item isKindOfClass:[TipTextItem class]]) 

													  {
														  TipTextItem *imageItem = (TipTextItem *)item;
														  
														  NSData *fileData = [imageItem.textContent dataUsingEncoding:4];;
														  [formData appendPartWithFileData:fileData
																					  name:[NSString stringWithFormat:@"%d",count] 
																				  fileName:[NSString stringWithFormat:@"%.txt",count]
																				  mimeType:@"text/plain"];
														  
														  

													  }
													  
												  }
												  
											  }
																  error:nil];
			
		}
		
		
	}
	
	AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
	
	[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
	 {
		 BaseResponse *response = nil;
		 response = [(BaseResponse *) [NSClassFromString(className) alloc] initWithResultData:responseObject];
		 if (!response)
		 {
			 response = [[BaseResponse alloc] initWithResultData:responseObject];
		 }
		 
		 response.httpResponseCode = operation.response.statusCode;
		 response.requestUrlString = urlString;
		 response.requestParamter  = object;
		 
		 
		 [response  saveToFileWithFileName:[[operation.request.URL absoluteString] md5String] withPath:[BaseCacheManager  cachePath]];
		 
		 if (finishBlock)
		 {
			 finishBlock(response);
		 }
	 }
											failure:^(AFHTTPRequestOperation *operation, NSError *error)
	 {
		 BaseResponse *response = nil;
		 
		 response = [[BaseResponse alloc] init];
		 response.success = NO;
		 response.httpResponseCode = [error code];
#ifdef TESTVERSION
		 response.status = [NSString stringWithFormat:@"%ld",(long)[error code]];
		 
		 response.desc = [error description];
#else
		 response.err_msg = kInternetConnectionError;
#endif
		 
		 //		 DLog(@"%@", error);
		 response.requestUrlString = urlString;
		 response.requestParamter  = temPostDictionary;
		 if (finishBlock)
		 {
			 finishBlock(response);
		 }
		 
		 
		 response.httpResponseCode = operation.response.statusCode;
		 response.requestUrlString = urlString;
		 response.requestParamter  = object;
		 
	 }];
	
	[requestOperation start];
	
	return  requestOperation;
	
}



- (void)getTipDetailByTipId:(NSString *)tipId finishBlock:(RequestFinishBlock)finishBlock
{
	//kGetTipDetailUrl
	
	if (CHECK_VALID_STRING(tipId))
	{		
		NSString *relativePath = [NSString stringWithFormat:@"%@/%@",kGetTipDetailUrl,tipId];
		
		WEAKSELF
		AFHTTPRequestOperation * requestOperation = [self beginGetRequestWithRelativePath:relativePath
																		  parameterObject:nil
																			responseClass:nil
																			  finishBlock:^(BaseResponse *response) 
													 {

														 if(response.success)
														 {
															 if (CHECK_VALID_DICTIONARY(response.object))
															 {
																 NSDictionary *dic = response.object;
																 TipInfo *tipInfo = [[TipInfo alloc] initWithSourceString:dic];
																 
																 NSDictionary *fileDic = [dic objectForKey:@"attachmentsName"];
																 
																 if (CHECK_VALID_DICTIONARY(fileDic))
																 {
																	 NSMutableArray *fileItemArray = [NSMutableArray array];
																	 NSArray *keyArray = [fileDic allKeys];
																	 for (NSString *key in keyArray) 
																	 {
																		 if ([key hasPrefix:@"txt"])
																		 {
																			 TipTextItem *tipTextItem = [[TipTextItem alloc] init];
																			 tipTextItem.textContent = [fileDic objectForKey:key];
																			 
																			 [fileItemArray addObject:tipTextItem];
																		 }
																		 else
																		 {
																			 TipImageItem *tipItem = [[TipImageItem alloc] init];
																			 tipItem.imageUrl = [fileDic objectForKey:key];
																			 
																			 [fileItemArray addObject:tipItem];
																			 
																			 if (!CHECK_VALID_STRING(tipInfo.firstImageUrlString)) 
																			 {
																				 tipInfo.firstImageUrlString = tipItem.imageUrl;
																			 }

																		 }
																	 }
																	 tipInfo.fileArray = fileItemArray;
																 }
																 
																 response.object = tipInfo;

															 }
															 
														 }
														 
														 finishBlock(response);
														 [weakSelf removeWrapperForKey:kGetTipDetailUrl];
														 
														 
													 }];
		
		[self setWrapper:requestOperation
				  ForKey:kGetTipDetailUrl];
	}

}




- (void)getTipsListWithTopicInfo:(TopicInfo *)topicInfp pageNumber:(NSInteger)pageNumber withFinishBlock:(RequestFinishBlock)finishBlock
{
	NSString *relativePath = [NSString stringWithFormat:@"%@%@",kGetTipsByTopic,topicInfp.topicId];
	NSDictionary *dictionary = @{@"curPage":@(pageNumber),@"pageSize":@(kDefaultPageSize)};

	WEAKSELF
	AFHTTPRequestOperation * requestOperation = [self beginGetRequestWithRelativePath:relativePath
																	  parameterObject:dictionary
																		responseClass:nil
																		  finishBlock:^(BaseResponse *response) {
																			  [weakSelf removeWrapperForKey:relativePath];
																			  
																			  
																			  NSMutableArray *resultArray = [NSMutableArray array];
																					NSArray *dicArray = [response.object objectForKey:@"pageContent"];
																					
																					for (NSDictionary *dic in dicArray)
																					{
																						TipAbstract *abstract = [[TipAbstract alloc] initWithSourceString:dic];
																						WaterFlowDisplayInfo *displayInfo = [WaterFlowDisplayInfo infoWithAbstract:abstract];
																						
																						[resultArray addObject:displayInfo];
																					}
																					response.object = resultArray;
																					
																			  finishBlock(response);

																			  
																		  }];
	
	
	
	
	[self setWrapper:requestOperation
			  ForKey:relativePath];
}


#pragma --
#pragma mark - 技巧收藏/点赞
- (void)priseTipsToServe:(NSString *)userId tipId:(NSString *)tipId finishBlock:(RequestFinishBlock)finishBlock
{
	[self handlePriseOrCollectionTipsToServe:userId
									   tipId:tipId
										type:@"praise"
								 finishBlock:finishBlock];
}

- (void)collectionTipsToServe:(NSString *)userId tipId:(NSString *)tipId finishBlock:(RequestFinishBlock)finishBlock
{
	[self handlePriseOrCollectionTipsToServe:userId
									   tipId:tipId
										type:@"collect"
								 finishBlock:finishBlock];
}

- (void)handlePriseOrCollectionTipsToServe:(NSString *)userId tipId:(NSString *)tipId type:(NSString *)type finishBlock:(RequestFinishBlock)finishBlock
{
	NSString *relativePath = [NSString stringWithFormat:@"%@%@/%@/%@",kPriseTipWithIdUrl,userId,type,tipId];
	
	
	WEAKSELF
	
	AFHTTPRequestOperation * requestOperation = [self beginRequestWithRelativePath:relativePath 
																   parameterObject:nil
																	 responseClass:nil
																	   finishBlock:^(BaseResponse *response) {
																		   finishBlock(response);
																		   [weakSelf removeWrapperForKey:kPublishTipsUrl];
																		   
																	   }];
	[self setWrapper:requestOperation
			  ForKey:kPublishTipsUrl];
}


@end
